import logging
from src.config_util import load_config
from src.websocket_app import WebSocketManager


class Signer:
    def __init__(self):
        self.config = load_config()
        # 卡介质密码
        self.password = self.config.get('account', 'password')

    def sign(self, data_str):
        """加签方法"""
        # 发送到海关客户端进行加签
        try:
            ws_manager = WebSocketManager()
            if ws_manager.is_connected_successfully(protocol="http"):
                result = ws_manager.sync_base_invoke(
                    method="cus-sec_SpcSignDataAsPEM",
                    args={"inData": data_str, "passwd": self.password},
                    timeout=1
                )
                if result.get("Data"):
                    return result.get("Data")[0]
                else:
                    return {
                        "is_error": True,
                        "message": result
                    }
        except Exception as e:
            logging.error(f"加签失败: {e}")
            return {
                "is_error": True,
                "message": e
            }

    def sign_and_send(self, business_data):
        """加签并发送到海关API"""
        try:
            # 加签
            signature = self.sign(business_data)
            # 请求数据封装发送到海关 TODO

            return signature
        except Exception as e:
            logging.error(f"发送数据失败: {e}")
            raise